﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleAppServer.Core;
using System.Net;

namespace SimpleAppServer.Implement.Socket
{
    /// <summary>
    /// Udp Session
    /// </summary>
    public class UdpSession : AbstractAppSession
    {
        System.Net.Sockets.Socket m_UdpServer = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sK">UdpServer Socket</param>
        /// <param name="token">UserToken</param>
        public UdpSession(System.Net.Sockets.Socket sK, EndPoint token)
            : base(token)
        {
            m_UdpServer = sK;
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>发送成功或失败</returns>
        public override bool Send(ICommand command)
        {
            try
            {
                byte[] buff = command.GetBytes();
                m_UdpServer.BeginSendTo(buff, 0, buff.Length, System.Net.Sockets.SocketFlags.None,
                  (EndPoint)this.UserToken,
                  new AsyncCallback(SendCallback), m_UdpServer);
            }
            catch (Exception ex)
            {
                logger.Debug(ex);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 异步回调方法
        /// </summary>
        /// <param name="iar">IAsyncResult</param>
        void SendCallback(IAsyncResult iar)
        {
            try
            {
                System.Net.Sockets.Socket sK = (System.Net.Sockets.Socket)iar.AsyncState;
                sK.EndSendTo(iar);
            }
            catch (Exception ex)
            {
                logger.Debug(ex);
            }
        }
    }
}
